﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Sales;

namespace NotebookS2
{
    public partial class ARDebitMemo : RibbonForm
    {
        public ARDebitMemo()
        {
            InitializeComponent();
        }

        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }

        public DataTable LineItems { get; set; }


        public void PrintPreview()
        {
            PRNT_ARDM oPrint = new PRNT_ARDM();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocNum.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }
        void InitializeSeries()
        {

            string _SERIES_CODE = "11";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            if (oSeries.IsAutoNumber(_SERIES_CODE) == true)
            {
                txtDocNum.Properties.ReadOnly = true;
                txtDocNum.Text = "##########";

            }
            oSeries.Close();

        }
        

        void DisableControls()
        {
            txtRemarks.Enabled = false;
            txtCardCode.Enabled = false;
            txtCardName.Enabled = false;
            btnAdd.Enabled = false;
            grdViewDebitMemo.OptionsBehavior.Editable = false;
        }

        void EnableControls()
        {
            
            txtRemarks.Enabled = true;
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            btnAdd.Enabled = true;
            grdViewDebitMemo.OptionsBehavior.Editable = true;

            
        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _DOCTYPE = "11";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_DOCTYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_DOCTYPE);
            }
            else
            {
                _SERIES = txtDocNum.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void RemoveBlankLastRowFirst()
        {
            try
            {
                int iCount = -1;
                grdViewDebitMemo.MoveLast();

                int[] oRow = grdViewDebitMemo.GetSelectedRows();

                iCount = oRow[0];
                string sItemCode = "";


                sItemCode = grdViewDebitMemo.GetRowCellValue(iCount, grdViewDebitMemo.Columns["AcctCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    grdViewDebitMemo.DeleteRow(iCount);
                }
            }
            catch
            {
            }

        }
        public void InitializeTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("AcctCode", typeof(string));
            dt.Columns.Add("AcctName", typeof(string));
            dt.Columns.Add("Particulars", typeof(string));
            dt.Columns.Add("Amount", typeof(double));

            this.LineItems = dt;
        }

        public void ShowSearch()
        {
            FND_ARDEBITMEMO oForm = new FND_ARDEBITMEMO();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            string _DOC_NUMBER = oForm.SelectedDocumentNumber;

            DebitMemoManager oManager = new DebitMemoManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable dt = new DataTable();

            dt = oManager.GetDebitMemo(_DOC_NUMBER);
            DataRow oRow = dt.Rows[0];

            txtDocNum.Text = _DOC_NUMBER;
            txtCardCode.Text = oRow["CardCode"].ToString();
            txtCardName.Text = oRow["CardName"].ToString();

            txtRemarks.Text = oRow["Remarks"].ToString();
            txtStatus.Text = oRow["DocStatus"].ToString();

            txtCreatedBy.Text = oRow["CreatedBy"].ToString();
            dtDateCreated.EditValue = Convert.ToDateTime(oRow["DateCreated"].ToString());
            txtModifiedBy.Text = oRow["ModifiedBy"].ToString();
            dtDateModified.EditValue = Convert.ToDateTime(oRow["DateModified"].ToString());
            txtTotalAmount.Text = oRow["TotalAmount"].ToString();

            this.LineItems = oManager.GetDebitMemoLineItems(_DOC_NUMBER);
            
            grdCntrlDebitMemo.DataSource = this.LineItems;
            grdCntrlDebitMemo.Refresh();

            ComputeTotal();

            oManager.Close();

            btnAdd.Text = "Update";

            if (txtStatus.Text == "Draft")
            {
                if (grdViewDebitMemo.RowCount == 0)
                {
                    grdViewDebitMemo.AddNewRow();
                }
            }

        }

        private void ARDebitMemo_Load(object sender, EventArgs e)
        {
            InitializeSeries();

            dtPostDate.EditValue = System.DateTime.Now;

            txtCreatedBy.Text = this.ActiveUserID;
            dtDateCreated.EditValue = System.DateTime.Now;
            txtModifiedBy.Text = this.ActiveUserID;
            dtDateModified.EditValue = System.DateTime.Now;
            
            InitializeTable();

            grdCntrlDebitMemo.DataSource = this.LineItems;
            grdCntrlDebitMemo.Refresh();

            grdViewDebitMemo.OptionsNavigation.EnterMoveNextColumn = true;
            if (grdViewDebitMemo.RowCount <= 0)
            {
                grdViewDebitMemo.AddNewRow();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            RemoveBlankLastRowFirst();

            DebitMemoManager oManager = new DebitMemoManager();
            DebitMemoUnit oUnit = new DebitMemoUnit();

            if (btnAdd.Text == "Add")
            {
                txtDocNum.Text = GetNewSeries();

                oUnit.DocNum = txtDocNum.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.DocStatus = txtStatus.Text;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.TotalAmount = Convert.ToDouble(txtTotalAmount.Text);

                oUnit.DocDate = Convert.ToDateTime(dtPostDate.EditValue);

                oUnit.DateCreated = Convert.ToDateTime(dtDateCreated.EditValue);
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = Convert.ToDateTime(dtDateModified.EditValue);
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.LineItems = this.LineItems;
                
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                oManager.AddDebitMemo(oUnit);

                oManager.Close();

                btnAdd.Text = "Update";

                if (txtStatus.Text == "Draft")
                {
                    if (grdViewDebitMemo.RowCount == 0)
                    {
                        grdViewDebitMemo.AddNewRow();
                    }
                }
            }
            else
            {
               
                oUnit.DocNum = txtDocNum.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.DocStatus = txtStatus.Text;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.TotalAmount = Convert.ToDouble(txtTotalAmount.Text);

                oUnit.DocDate = Convert.ToDateTime(dtPostDate.EditValue);

                oUnit.DateCreated = Convert.ToDateTime(dtDateCreated.EditValue);
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = Convert.ToDateTime(dtDateModified.EditValue);
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.LineItems = this.LineItems;
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                oManager.UpdateDebitMemo(oUnit);

                oManager.Close();

                btnAdd.Text = "Update";

                if (txtStatus.Text == "Draft")
                {
                    if (grdViewDebitMemo.RowCount == 0)
                    {
                        grdViewDebitMemo.AddNewRow();
                    }
                }
            }
        }

        void CancelDocument()
        {
            if (MessageBox.Show("Are you sure you want to Cancel this Document?", "Cancel Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                DebitMemoManager oManager = new DebitMemoManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                txtStatus.Text = "Canceled";
                oManager.CancelDocument(txtDocNum.Text);

                oManager.Close();
            }

        }

        void PostDocument()
        {
            if (MessageBox.Show("Are you sure you want to post this Document?", "Post Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                DebitMemoManager oManager = new DebitMemoManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                txtStatus.Text = "Posted";
                oManager.PostDocument(txtDocNum.Text);

                oManager.Close();

                
            }

        }

        void CloseDocument()
        {
            if (MessageBox.Show("Are you sure you want to close this Document?", "Close Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                DebitMemoManager oManager = new DebitMemoManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                txtStatus.Text = "Closed";
                oManager.CloseDocument(txtDocNum.Text);

                oManager.Close();
            }

        }
        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Index)
            {
                case 0:
                     // Post
                 
                        PostDocument();
                    
                    break;
                case 1:
                    // Cancel:
                    if (txtStatus.Text == "Draft")
                    {
                        CancelDocument();
                    }
                    else if (txtStatus.Text == "Posted")
                    {
                        CloseDocument();
                    }
                    break;
            }
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Posted")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

            if (txtStatus.Text == "Draft")
            {
                EnableControls();
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

            if (txtStatus.Text == "Canceled")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }

            if (txtStatus.Text == "Closed")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }
        }

        private void grdViewDebitMemo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (MessageBox.Show("Are you sure you want to delete this row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    grdViewDebitMemo.DeleteRow(grdViewDebitMemo.FocusedRowHandle);
                }
            }

            if (e.KeyCode == Keys.Down)
            {
                if (grdViewDebitMemo.IsLastRow)
                {

                    string sItemCode = "";

                    int iCount = grdViewDebitMemo.FocusedRowHandle;
                    sItemCode = grdViewDebitMemo.GetRowCellValue(iCount, grdViewDebitMemo.Columns["AcctCode"]).ToString();

                    if (sItemCode != "" && (txtStatus.Text == "Draft"))
                    {
                        grdViewDebitMemo.AddNewRow();

                        grdCntrlDebitMemo.Select();
                        grdViewDebitMemo.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        grdViewDebitMemo.FocusedColumn = grdViewDebitMemo.Columns["AcctCode"];
                        grdViewDebitMemo.ShowEditor();


                    }
                }
            }
        }

        private void txtAcctCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_GLACCOUNT oForm = new FND_GLACCOUNT();

            oForm.ConnectionString = this.ConnectionString;

            oForm.ShowDialog();

            grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["AcctCode"], oForm.SelectedGLAcctCode);
            grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["AcctName"], oForm.SelectedGLAcctName);


        }

        void ComputeTotal()
        {
            double _Total = 0;

            foreach(DataRow oRow in this.LineItems.Rows)
            {
                if (oRow["Amount"] != DBNull.Value)
                {
                    _Total = _Total + Convert.ToDouble(oRow["Amount"]);
                }
            }

            txtTotalAmount.Text = _Total.ToString("#,###.00");
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtAcctCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_ACCOUNTCODE = (DevExpress.XtraEditors.TextEdit)sender;

                ChartOfAccountManager oManager = new ChartOfAccountManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable dt = oManager.GetChartOfAccountByAcctCode(_TEXT_ACCOUNTCODE.Text);
                oManager.Close();


                if (dt.Rows.Count > 0)
                {
                    DataRow oRow = dt.Rows[0];

                    string sAcctCode = oRow["AcctCode"].ToString();
                    string sAcctName = oRow["AcctName"].ToString();
                    grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["AcctCode"], sAcctCode);
                    grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["AcctName"], sAcctName);


                }

                else
                {

                    FND_GLACCOUNT oForm = new FND_GLACCOUNT();

                    DevExpress.XtraEditors.TextEdit eGLAccount = (DevExpress.XtraEditors.TextEdit)sender;

                    oForm.ConnectionString = this.ConnectionString;
                    oForm.SetSearch(eGLAccount.Text);
                    oForm.ShowDialog();

                    grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["AcctCode"], oForm.SelectedGLAcctCode);
                    grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["AcctName"], oForm.SelectedGLAcctName);

                }
                //grdViewDebitMemo.FocusedColumn = grdViewDebitMemo.Columns["Particulars"];
            
            }
        }

        private void txtAmount_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Down)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_AMOUNT = (DevExpress.XtraEditors.TextEdit)sender;

                grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["Amount"], _TEXT_AMOUNT.Text);
                grdViewDebitMemo.FocusedColumn = grdViewDebitMemo.Columns["AcctCode"];
                grdViewDebitMemo.ShowEditor();

                ComputeTotal();
            }

            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_AMOUNT = (DevExpress.XtraEditors.TextEdit)sender;

                grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["Amount"], _TEXT_AMOUNT.Text);
                grdViewDebitMemo.FocusedColumn = grdViewDebitMemo.Columns["AcctCode"];
                grdViewDebitMemo.ShowEditor();

                SendKeys.Send("{DOWN}");

                ComputeTotal();
            }

            if (e.KeyCode == Keys.Tab)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_AMOUNT = (DevExpress.XtraEditors.TextEdit)sender;

                grdViewDebitMemo.SetRowCellValue(grdViewDebitMemo.FocusedRowHandle, grdViewDebitMemo.Columns["Amount"], _TEXT_AMOUNT.Text);
                grdViewDebitMemo.FocusedColumn = grdViewDebitMemo.Columns["AcctCode"];
                grdViewDebitMemo.ShowEditor();

                SendKeys.Send("{DOWN}");

                ComputeTotal();
            }
        }

        private void grdViewDebitMemo_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
        }

        private void txtCardCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();
            
            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {

             
                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.ShowDialog();

                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
            }
            catch
            {
            }
        }
    }
}
